const fs = require('fs')
const fetcher = require('./fetcher.js')
const Jubi = require('./jubi.js').Jubi
const Bter = require('./bter.js').Bter


let configFilePath = "./config.json"
let config = JSON.parse(fs.readFileSync(configFilePath, 'utf8'))
// console.log(config);

setInterval(getTickers, 10*1000);

// function canMoveBrick(plat1, plat2) {
// 	if (plat1.getSellPrice < plat2.getBuyPrice)
// 		return [ticker1, ticker2]
// 	if (plat1.getBuyPrice > plat2.getSellPrice) 
// 		return [ticker2, ticker1]
// }

function canMoveBrick(plat1, plat2) {
	// console.log('^^^'+plat1)
	if ( plat1.getSellPrice() < plat2.getBuyPrice() )
		return [plat1, plat2]
	else if ( plat1.getBuyPrice() > plat2.getSellPrice() ) 
		return [plat2, plat1]
	else {
		console.log('Error in canMoveBrick')
		console.log(plat1)
		console.log(plat2)
	}
}


// let plat1
// let plat2

let jubiPlat
let bterPlat


function onFetchTicker(plat, ticker) {
	// console.log('===================')
	// console.log(plat.name)
	// console.log(ticker)

	plat.ticker = ticker

	// let sellPrice = plat.getSellPrice()
	// console.log(plat.name+' lowest sell price '+sellPrice)
	// let buyPrice = plat.getBuyPrice()
	// console.log(plat.name+' highest buy price '+buyPrice)

	if (plat == Jubi) {
		// console.log('Jubi Ticker')
		jubiPlat = plat
	}
	else if (plat == Bter) {
		bterPlat = plat
	}

	//判断是否有套利空间
	if (jubiPlat && bterPlat) {
		let [fromPlat, toPlat] = canMoveBrick(jubiPlat, bterPlat)
		console.log('************************************')
		console.log('存在套利空间')
		console.log(fromPlat.name + ' sell : ' +fromPlat.getSellPrice() + ' ==> ' + toPlat.name + ' buy : ' + toPlat.getBuyPrice() )
		

		let sellPrice = fromPlat.getSellPrice()
		let buyPrice = toPlat.getBuyPrice()
		let diff = (buyPrice - sellPrice)
		let sum  = (Number(buyPrice) + Number(sellPrice))
		// console.log(diff)
		// console.log(sum)
		let ratio = diff / sum - 0.001
		console.log('收益率： '+ratio)

		console.log('************************************')
	}
}


function getTickers() {
	// console.log('sdfasg ');
	// fetcher.fetchTicker();

	// let jb = new Jubi()
	// console.log(jb)
	// console.log(jb.name)
	// console.log(jb.nxtTickerPath)

	// console.log(Jubi.nxtTickerPath)

	fetcher.fetchTicker(Jubi, Jubi.nxtTickerPath, onFetchTicker)
	fetcher.fetchTicker(Bter, Bter.nxtTickerPath, onFetchTicker)
}

getTickers()
